from bson import ObjectId
from datetime import datetime
from .. import db

class Decision:
    def __init__(self, field_id, decision_type, analysis_result=None, 
                 recommendation=None, created_at=None, _id=None):
        self.field_id = field_id
        self.decision_type = decision_type
        self.analysis_result = analysis_result or {}
        self.recommendation = recommendation or {}
        self.created_at = created_at or datetime.utcnow()
        self._id = _id

    def save(self):
        decision_data = {
            'field_id': self.field_id,
            'decision_type': self.decision_type,
            'analysis_result': self.analysis_result,
            'recommendation': self.recommendation,
            'created_at': self.created_at
        }
        
        if not self._id:
            result = db.decisions.insert_one(decision_data)
            self._id = result.inserted_id
        else:
            db.decisions.update_one(
                {'_id': self._id},
                {'$set': decision_data}
            )
        return self

    @staticmethod
    def find_by_id(decision_id):
        try:
            decision_data = db.decisions.find_one({'_id': ObjectId(decision_id)})
            if decision_data:
                return Decision(
                    field_id=decision_data['field_id'],
                    decision_type=decision_data['decision_type'],
                    analysis_result=decision_data.get('analysis_result', {}),
                    recommendation=decision_data.get('recommendation', {}),
                    created_at=decision_data.get('created_at'),
                    _id=decision_data['_id']
                )
        except:
            return None
        return None

    @staticmethod
    def find_by_field(field_id, decision_type=None, limit=10):
        query = {'field_id': field_id}
        if decision_type:
            query['decision_type'] = decision_type
            
        return [
            Decision(
                field_id=d['field_id'],
                decision_type=d['decision_type'],
                analysis_result=d.get('analysis_result', {}),
                recommendation=d.get('recommendation', {}),
                created_at=d.get('created_at'),
                _id=d['_id']
            )
            for d in db.decisions.find(query).sort('created_at', -1).limit(limit)
        ]

    def to_dict(self):
        return {
            'id': str(self._id),
            'field_id': str(self.field_id),
            'decision_type': self.decision_type,
            'analysis_result': self.analysis_result,
            'recommendation': self.recommendation,
            'created_at': self.created_at.isoformat()
        } 